import React, { Component } from 'react';
import { Menu, Icon } from 'antd';
import { NavLink } from 'react-router-dom';
import { connect } from 'react-redux';
import MenuConfig from '../../config/menuConfig';
import { switchMenu } from '../../redux/action';
import './index.less';

import logo from '../../assets/logo-ant.svg';

const { SubMenu } = Menu;

class NavLeft extends Component {
  state = {
    currentKey: '',
  };
  // 菜单点击
  handleClick = ({ item, key }) => {
    if (key == this.state.currentKey) {
      return false;
    }
    // 事件派发，自动调用reducer，通过reducer保存到store对象中
    const { onSwitchMenu } = this.props;
    onSwitchMenu(item.props.title);

    this.setState({
      currentKey: key,
    });
  };

  homeHandleClick = () => {
    const { onSwitchMenu } = this.props;
    onSwitchMenu('首页');
    this.setState({
      currentKey: '',
    });
  };

  // 组件加载生命周期
  componentWillMount() {
    const menuTreeNode = this.renderMenu(MenuConfig);
    this.setState({
      menuTreeNode,
    });
  }

  // 菜单渲染
  renderMenu = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <SubMenu title={item.title} key={item.key}>
            {this.renderMenu(item.children)}
          </SubMenu>
        );
      } else {
        return (
          <Menu.Item title={item.title} key={item.key}>
            <NavLink to={item.key}>{item.title}</NavLink>
          </Menu.Item>
        );
      }
    });
  };

  render() {
    return (
      <div>
        <NavLink to="home" onClick={this.homeHandleClick}>
          <div className="logo">
            <img src={logo} alt="" />
            <h1>Imooc MS</h1>
          </div>
        </NavLink>
        <Menu theme="dark" onClick={this.handleClick}>
          {this.state.menuTreeNode}
        </Menu>
      </div>
    );
  }
}

export default connect(null, (dispatch) => {
  return {
    onSwitchMenu: (title) => dispatch(switchMenu(title)),
  };
})(NavLeft);
